package main

import (
	"gitee.com/zhangyu520cw/basic-go/webook/internal/repository"
	"gitee.com/zhangyu520cw/basic-go/webook/internal/repository/dao"
	"gitee.com/zhangyu520cw/basic-go/webook/internal/service"
	"gitee.com/zhangyu520cw/basic-go/webook/internal/web"
	login2 "gitee.com/zhangyu520cw/basic-go/webook/internal/web/middlewares/login"
	"gitee.com/zhangyu520cw/basic-go/webook/pkg/ginx/middleware/ratelimit"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/memstore"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strings"
	"time"
)

func main() {
	db := initDB()
	server := initWebServer()
	server = initUser(server, db)
	server.Run(":8080")
}

//func initServer(hdl *web.UserHandle) *gin.Engine {
//
//}

func initDB() *gorm.DB {
	db, err := gorm.Open(mysql.Open("root:123456@tcp(localhost:3306)/webook?charset=utf8mb4&parseTime=True&loc=Local"))
	if err != nil {
		panic(err)
	}
	err = dao.InitTables(db)
	if err != nil {
		panic(err)
	}
	return db
}

func initUser(server *gin.Engine, db *gorm.DB) *gin.Engine {
	ud := dao.NewUserDao(db)
	ur := repository.NewRepository(ud)
	us := service.NewUserService(ur)
	hdl := web.NewUserHandle(*us)
	hdl.RegisterRouters(server)
	return server
}

func initWebServer() *gin.Engine {
	server := gin.Default()
	redisClient := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	server.Use(ratelimit.NewBuilder(redisClient, time.Second, 100).Build())
	server.Use(cors.New(cors.Config{
		AllowCredentials: true,
		//AllowAllOrigins:  true,
		AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
		AllowHeaders: []string{"Content-Type", "Authorization"},
		// 这个是允许前端访问你的后端相应中带的头部
		ExposeHeaders: []string{"x-jwt-token"},
		AllowOriginFunc: func(origin string) bool {
			if strings.Contains(origin, "172.29.31.13") {
				return true
			}
			return strings.HasPrefix(origin, "http://company.com")
		},
		MaxAge: 12 * time.Hour,
	}))
	//useSession(server)
	useJwt(server)
	return server
}

func useJwt(server *gin.Engine) {
	login := &login2.LoginJWTMiddlewareBuilder{}
	server.Use(login.CheckLogin())
}

func useSession(server *gin.Engine) {
	login := &login2.LoginMiddlewareBuilder{}
	// 存储数据的
	// 直接存cookie
	//store := cookie.NewStore()
	// 基于内存的实现
	store := memstore.NewStore([]byte("nX0mH3hM2zJ3dA2aU4iW3hK2dY2pO1jZ"),
		[]byte("dN5xQ7iS8kC3dA8bA9eD4kA6iR2bO3kG"))
	//store, err := redis.NewStore(16, "tcp", "localhost:6379",
	//	"", []byte("nX0mH3hM2zJ3dA2aU4iW3hK2dY2pO1jZ"),
	//	[]byte("dN5xQ7iS8kC3dA8bA9eD4kA6iR2bO3kG"))
	//if err != nil {
	//	panic(err)
	//}
	server.Use(sessions.Sessions("ssid", store), login.CheckLogin())
}
